package com.etrans.web.gps.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;

public class TreeCommon {
	//@EtCommentAnnotation(type = "final", desc = "创建递归树")
	public static List<Map<String, Object>> createTree(
			List<HashMap<String, Object>> listTree, int level) {
		Map<String, Object> map = null;
		List<Map<String, Object>> parentList = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < listTree.size(); i++) {
			map = null;
			HashMap<String, Object> perUnit = listTree.get(i);
			if (perUnit.get("FullID") == null) {
				continue;
			}
			String FullID = perUnit.get("FullID").toString();
			String ID = perUnit.get("ID").toString();
			String Name = perUnit.get("Name").toString();

			if (FullID.length() == level) {
				map = new HashMap<String, Object>();
				map.put("id", ID);
				map.put("text", Name);
				map.put("children", GetChildren(FullID, i, listTree));
			}
			if (map != null)
				parentList.add(map);
		}
		return parentList;
	}


	/**
	 * 获取当前节点的所有子节点
	 * @param FullID
	 * @param index
	 * @return
	 */
	private static List<Map<String, Object>> GetChildren(String FullID,
			int index, List<HashMap<String, Object>> treeList) {
		List<Map<String, Object>> childList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> cacheChildList = null;
		Map<String, Object> childMap = null;
		Map<String, Object> resultMap = null;
		String childFullID = "";
		for (int i = index + 1; i < treeList.size(); i++) {
			childMap = treeList.get(i);
			childFullID = childMap.get("FullID").toString().trim();
			if (childFullID.length() < 9) {
				continue;
			}
			// 查找子节点
			if (childFullID.length() > FullID.length()
					&& childFullID.substring(0, childFullID.length() - 9)
							.trim().equals(FullID)) {
				resultMap = new HashMap<String, Object>();
				cacheChildList = new ArrayList<Map<String, Object>>();
				resultMap.put("id", childMap.get("ID").toString());
				resultMap.put("text", childMap.get("Name").toString());
				cacheChildList = GetChildren(childFullID, i, treeList);
				resultMap.put("children", cacheChildList);
				childList.add(resultMap);
				i = i + GetChildCount(cacheChildList);

			} else {
				break;
			}
		}
		return childList;
	}
    
	/**
	 * 获取子节点个数
	 * @param ChildList
	 * @return
	 */
	private static int GetChildCount(List<Map<String, Object>> ChildList) {
		String jsonChild = JSON.toJSONString(ChildList);
		if (jsonChild.indexOf("text") != -1) {
			String ArrayChild[] = jsonChild.split("\"text\"");
			return ArrayChild.length-1;
		} else {
			return 0;
		}
	}

}
